package com.edushare.common.dao;

import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.QueryCacheStrategy;
import org.apache.cayenne.query.SelectQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edushare.common.constants.ConfigPropertyName;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.ConfigProperties;

public class ConfigPropertiesDAO extends CayenneBasedDAO {

	private Log log = LogFactory.getLog(ConfigPropertiesDAO.class);
	
	public ConfigPropertiesDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}
	
	public List<ConfigProperties> getAllProperties(){
		SelectQuery query = new SelectQuery(ConfigProperties.class);
		return getDataContext().performQuery(query);
	}
	
	/**
	 * <p>
	 * get configuration properties -- NOTE THAT THIS USES CACHE.
	 * use getConfigProperty(String propertyName, boolean useCache) with useCache = false 
	 * to fetch fresh data from Database.
	 * </p>
	 * 
	 */
	public ConfigProperties getConfigProperty(String propertyName){
		return getConfigProperty(propertyName, true);
	}
	
	/**
	 * <p>
	 * gets config property from cache(fast) or from DB(slow)
	 * This method should be used for most of the purposes
	 * </p>
	 * 
	 * @param propertyName
	 * @param useCache
	 * @return
	 */
	public ConfigProperties getConfigProperty(String propertyName, boolean useCache){
		Expression exp = Expression.fromString("name=$propName");
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("propName", propertyName);
		SelectQuery query = new SelectQuery(ConfigProperties.class, exp.expWithParameters(hm));
		if(!useCache)
			query.setCacheStrategy(QueryCacheStrategy.NO_CACHE);
		List<ConfigProperties> props = getDataContext().performQuery(query);
		if(props!=null && props.size()>0){
			return props.get(0);
		}
		return null;
	}
	
	/**
	 * gets Backup status from database. It does not uses cache.
	 */
	public int getBackupStatus(){
		ConfigProperties p = getConfigProperty(ConfigPropertyName.SYSTEM_BACKUP_STATUS, false);
		String val = p.getValue();
		int value = 0;
		try{
			value = Integer.parseInt(val);
		}catch(NumberFormatException nfe){
			//ignore
			log.warn("**** SYSTEM BACKUP STATUS IS WRONG. ****");
		}
		
		return value;
	}

}
